<template>
    <div>
      <h2>批量上传单选题目</h2>
      <input type="file" @change="handleFileUpload" />
      <button @click="uploadQuestions" :disabled="isUploading">上传</button>
      <p v-if="isUploading">上传中，请稍候...</p>
      <p v-if="uploadMessage">{{ uploadMessage }}</p>
    </div>
  </template>
  
  <script>
  import * as XLSX from "xlsx";
  import axios from "axios";
  import { ref } from "vue";
  export default {
    setup() {
      const questions = ref([]); // 存储解析后的题目数据
      const isUploading = ref(false); // 上传状态
      const uploadMessage = ref(""); // 上传结果消息
      const currentProgress = ref(0); // 当前上传进度
  
      // 解析上传的 Excel 文件
      const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (!file) {
          uploadMessage.value = "请上传文件！";
          return;
        }
  
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: "array" });
          const sheetName = workbook.SheetNames[0]; // 获取第一个工作表
          const worksheet = workbook.Sheets[sheetName];
  
          // 转换为 JSON 数据
          const jsonData = XLSX.utils.sheet_to_json(worksheet);
          questions.value = jsonData.map((row) => ({
            content: {
              stem: row["题目"],
              options: [
                { key: "A", content: row["选项A"] },
                { key: "B", content: row["选项B"] },
                { key: "C", content: row["选项C"] },
                { key: "D", content: row["选项D"] },
              ],
            },
            answer: [row["答案"]],
            analysis: row["解析"],
            type: row["题目类型"],
            section_id: row["章节"],
          }));
        };
  
        reader.readAsArrayBuffer(file);
      };
  
      // 上传题目数据
      const uploadQuestions = async () => {
        if (!questions.value.length) {
          uploadMessage.value = "没有可上传的题目数据！";
          return;
        }
  
        isUploading.value = true;
        uploadMessage.value = "";
        currentProgress.value = 0;
  
        try {
          for (let i = 0; i < questions.value.length; i++) {
            const question = questions.value[i];
            const formData = new FormData();
            formData.append("content", JSON.stringify(question.content));
            formData.append("answer", JSON.stringify(question.answer));
            formData.append("analysis", question.analysis);
            formData.append("type", question.type);
            formData.append("section_id", question.section_id);
  
            // 调用接口上传单个题目
            let res=await axios.post(
              "http://172.20.64.14:8000/api/admin/question/upload/",
              formData,
              { headers: { "Content-Type": "multipart/form-data" } }
            );
            console.log(res);
            
            // 更新上传进度
            currentProgress.value = ((i + 1) / questions.value.length) * 100;
          }
  
          uploadMessage.value = "所有题目上传成功！";
        } catch (error) {
          uploadMessage.value = `上传失败：${error.message || "未知错误"}`;
        } finally {
          isUploading.value = false;
        }
      };
  
      return {
        handleFileUpload,
        uploadQuestions,
        isUploading,
        uploadMessage,
        currentProgress,
      };
    },
  };
  </script>
  
  <style>
  /* 可选：为进度条增加样式 */
  .progress-bar {
    width: 100%;
    background-color: #f3f3f3;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-top: 10px;
    position: relative;
    height: 20px;
  }
  .progress-bar-inner {
    height: 100%;
    background-color: #4caf50;
    width: 0;
    transition: width 0.2s ease;
  }
  </style>
  